package com.hnblc.blcwms.persistent.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.hnblc.blcwms.persistent.datasource.DBTypeEnum;
import com.hnblc.blcwms.persistent.datasource.DynamicDataSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@MapperScan(basePackages = {"com.hnblc.blcwms.persistent.**.mapper"})
@Configuration
public class MultiDatasourceConfig {


    Logger logger = LoggerFactory.getLogger(MultiDatasourceConfig.class);

    /**
     * DTS rabbit mq 分布式事务管理器
     * @param connectionFactory
     * @return
     */
    /*@Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
        return new RabbitAdmin(connectionFactory);
    }*/

    /**
     * mybatis-plus SQL执行效率插件【生产环境可以关闭】
     */
    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
    }


    @Bean(name = "apiDB")
    @ConfigurationProperties(prefix = "spring.datasource.druid.api" )
    public DataSource apiDB () {
        logger.debug("create interface datasource");
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "businessDB")
    @ConfigurationProperties(prefix = "spring.datasource.druid.business" )
    public DataSource businessDB () {
        logger.debug("create business datasource");
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "ecssentDB")
    @ConfigurationProperties(prefix = "spring.datasource.druid.ecssent" )
    public DataSource ecssentDB () {
        logger.debug("create ecssent datasource");
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * 动态数据源配置
     * @return
     */
    @Bean
    @Primary
    public DataSource multipleDataSource (@Qualifier("apiDB") DataSource apiDB,
                                          @Qualifier("businessDB") DataSource businessDB,
                                          @Qualifier("ecssentDB") DataSource ecssentDB
                                            ) {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        Map< Object, Object > targetDataSources = new HashMap<>();
        targetDataSources.put(DBTypeEnum.apiDB.getValue(), apiDB );
        targetDataSources.put(DBTypeEnum.businessDB.getValue(), businessDB);
        targetDataSources.put(DBTypeEnum.ecssentDB.getValue(), ecssentDB);
        dynamicDataSource.setTargetDataSources(targetDataSources);
        dynamicDataSource.setDefaultTargetDataSource(apiDB);
        return dynamicDataSource;
    }

    @Bean("sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(multipleDataSource(apiDB(),businessDB(),ecssentDB()));
//        sqlSessionFactory.setMapperLocations(resolver.getResources("classpath*:/mapperxml/microtek/*.xml"));
        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:/com/hnblc/blcwms/persistent/**/*.xml"));
        MybatisConfiguration configuration = new MybatisConfiguration();
        //configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setCacheEnabled(false);


        sqlSessionFactory.setConfiguration(configuration);
        sqlSessionFactory.setPlugins(new Interceptor[]{ //PerformanceInterceptor(),OptimisticLockerInterceptor()
                paginationInterceptor() //添加分页功能
        });
        sqlSessionFactory.setGlobalConfig(globalConfiguration());
        return sqlSessionFactory.getObject();
    }

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
    @Bean
    public GlobalConfig globalConfiguration() {
        GlobalConfig conf = new GlobalConfig();
        conf.setDbConfig(new GlobalConfig.DbConfig().setIdType(IdType.UUID));
        return conf;
    }
}
